#!/usr/bin/env python
# coding=utf-8

if __name__ == '__main__':
    """ for file debug"""
    import sys,os
    sys.path.insert(0,os.path.join( os.getcwd(), '..' ))

import threading,time
import vavava.basethread
from queue import Queue
from vavava.workshop import WorkShop

__author__ = 'vavava'

class BaseHandler(object):
    def __init__(self):
        pass

class Package(object):
    def __init__(self,work,begin_time=None,end_time=None,period=None):
        self.begin_time=begin_time
        self.end_time=end_time
        self.period=period
        self.work=work

class SynDict(object):
    def __init__(self):
        self._dict = {}
        self._mt = threading.Lock()

    def add(self,k,v):
        self._mt.acquire()
        self._dict[k]=v
        self._mt.release()

    def popitem(self):
        v = None
        self._mt.acquire()
        if len(self._dict) > 0:
            k,v = self._dict.popitem()
        self._mt.release()
        return v

class Dispatcher(vavava.basethread.BaseThread):
    """"""
    def __init__(self,workshop,log=None):
        vavava.basethread.BaseThread.__init__(self,"<Dispatcher>",log)
        self._ex = WorkShop()
        self._ex = workshop
        self._q1 = Queue()
        self._q_dict = SynDict()

    def AddPackage(self,work,begin_time=None,end_time=None,period=None):
        pa=Package(work,begin_time,end_time,period)
        if begin_time:
            self._q_dict.add(pa.begin_time,pa)
        else:
            self._q1.put(pa)

    def run(self):
        tb = time.clock()
        while self.IsRunning:
            tb = time.clock()

            if not self._q1.empty():
                pa=self._q1.get()
                self._ex.AddTask(pa.work)
                if pa.period:
                    now = time.time()
                    pa.begin_time = now + pa.period
                    self._q_dict.add(pa.begin_time,pa)
                #if __debug__: self.log.debug("Add a package")

            now = time.time()
            pa=self._q_dict.popitem()
            if pa:
                if pa.begin_time <= now:
                    self._q1.put(pa)
                else:
                    self._q_dict.add(pa.begin_time,pa)

            te = time.clock()
            interval = te-tb
            if interval < 0.5:
                time.sleep(0.5 - interval)



# test ...............

import vavava.workqueue,vavava.base
class twork(vavava.workqueue.work):
    def __init__(self,log=None):
        self.log = vavava.base.LogAdapter(log)

    def do(self):
        self.log.debug("working %f"%time.time())

if __name__ == "__main__":
    #from spiders.track_gripper import TrackGripperWork
    from vavava.workshop import WorkShop

    item_list=['MHB0012826', 'MHB0014533', 'MHB0015094', 'MHB0015088', 'MHB0015168',
               'MHB0015572', 'MHB0015729', 'UCL0000623','UQV0000030', 'UCL0000816',
               'MHB0016239', 'UQV0000071', 'UCL0000935', 'UCL0001042', 'UCL0001036',
               'UCL0001080', 'UQV0000117', 'UQV0000126']

    ws = WorkShop()
    ws.StartWork()

    dispatcher = Dispatcher(ws)
    dispatcher.running_start()

    try:
        """

        for item in item_list:
            tgw = TrackGripperWork(item)
            #pa = Package(tgw)
            dispatcher.AddPackage(tgw)
"""
        tgw = twork()
        dispatcher.AddPackage(tgw,period=1)
        while True:
            time.sleep(1)
    except(KeyboardInterrupt):
        print('main thread(%f):stop'%time.clock())
        dispatcher.running_stop()
        print('main thread(%f):stopped'%time.clock())









